package com.wenyu.wenyuyuedu.activity.circle;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.activity.personage.Help_FeedBack_Activity;
import com.wenyu.wenyuyuedu.activity.personage.MyPublishActivity;
import com.wenyu.wenyuyuedu.activity.personage.OtherPublishActivity;
import com.wenyu.wenyuyuedu.adapter.circleAdapter.SearchResultListViewAdapter;
import com.wenyu.wenyuyuedu.adapter.circleAdapter.SearchResultRecyclerAdapter;
import com.wenyu.wenyuyuedu.bean.JudgeWhetherJoinBean;
import com.wenyu.wenyuyuedu.bean.SearchActivityBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.circle.SearchServer;
import com.wenyu.wenyuyuedu.server.homepager.JudgeWhetherJoin;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.R.attr.value;

/*
* 搜索结果的展示
* */
public class SearchResultActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.circle_et_sousuo)
    EditText circleEtSousuo;
    @InjectView(R.id.search_quit)
    TextView searchQuit;
    @InjectView(R.id.search_tv_user)
    TextView searchTvUser;
    @InjectView(R.id.search_recycler)
    RecyclerView searchRecycler;
    @InjectView(R.id.search_tv_circle_name)
    TextView searchTvCircleName;
    @InjectView(R.id.search_lv)
    ListView searchLv;
    @InjectView(R.id.yonghu_circlr)
    TextView yonghuCirclr;
    private Intent intent;
    private Activity activity;
    private SearchResultListViewAdapter circleAdapter;
    private SearchResultRecyclerAdapter userAdapter;
    private Intent intents;
    private String searchkey;
    private List<SearchActivityBean.UserBean> user = new ArrayList<>();
    private List<SearchActivityBean.CircleBean> circle = new ArrayList<>();
    private String user_id;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_result);
        ButterKnife.inject(this);
        StatusBarUtil.setStatusBar(SearchResultActivity.this, R.color.white);
        activity = SearchResultActivity.this;
        initRecyclerView();
        setAdapterAndClick();
        initView();
        requestData();
    }

    /*请求数据*/
    private void requestData() {
        if(TextUtils.isEmpty(searchkey)){
            MyToast.showToast(SearchResultActivity.this,"请输入搜索内容",Toast.LENGTH_SHORT);
        }else {
            String token = AbSharedUtil.getString(activity, SharedConstants.USER_TOKEN);
            // 调用搜索的API方法
            SearchServer searchServer = ApiWrapper.getInstance().create(SearchServer.class);
            Call<SearchActivityBean> searchResult = searchServer.getSearchResult(token, searchkey);
            searchResult.enqueue(new Callback<SearchActivityBean>() {
                @Override
                public void onResponse(Call<SearchActivityBean> call, Response<SearchActivityBean> response) {
                    SearchActivityBean body = response.body();
                    if (body != null) {
                        int code = body.getCode();
                        if (code == 1) {
                            user_id = body.getUser_id();
                            user = body.getUser();
                            circle = body.getCircle();
                            fillData();
                        } else if (code == 0) {
                            showLoginDoalog();
                        } else if (code == 4301) {
                            MyToast.showToast(activity, "暂无搜索数据", Toast.LENGTH_SHORT);
                            if(user != null || user.size() != 0){
                                user.clear();
                                userAdapter.notifyDataSetChanged();
                            }
                            if(circle != null || circle.size() != 0){
                                circle.clear();
                                circleAdapter.notifyDataSetChanged();
                            }
                            fillData();
                        }
                    }
                }

                @Override
                public void onFailure(Call<SearchActivityBean> call, Throwable t) {
                    MyToast.showToast(activity, "网络异常，请稍后重试", Toast.LENGTH_SHORT);
                }
            });
        }
    }

    /*token错误或失效*/
    AlertDialog adLogin;
    private TextView quxiaoLogin;
    private TextView quedingLogin;

    private void showLoginDoalog() {

        adLogin = new AlertDialog.Builder(activity).create();
        adLogin.show();
        Window window = adLogin.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiaoLogin = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        quedingLogin = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiaoLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adLogin.dismiss();
            }
        });
        quedingLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intent.setClass(activity, LoginActivity.class);
                startActivity(intent);
                adLogin.dismiss();
            }
        });
    }

    /*设置adpter和点击事件*/
    private void setAdapterAndClick() {
        userAdapter = new SearchResultRecyclerAdapter(activity);
        searchRecycler.setAdapter(userAdapter);
        /*书圈的adapter*/
        circleAdapter = new SearchResultListViewAdapter(activity);
        searchLv.setAdapter(circleAdapter);
        userAdapter.setOnItemClickListener(new SearchResultRecyclerAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, SearchActivityBean.UserBean data) {
                int is_lander = data.getIs_lander();
                /*0代表不是自己*/
                if (is_lander == 0) {
                    String uid = data.getUid();
                    intents.setClass(SearchResultActivity.this, OtherPublishActivity.class);
                    intents.putExtra("userid", uid);
                    startActivity(intents);
                } else if (is_lander == 1) {
                    /*1代表是用户自己*/
                    intents.setClass(activity, MyPublishActivity.class);
                    startActivity(intents);
                }
            }
        });
        searchLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String id = circle.get(i).getId();
                String title = circle.get(i).getTitle();
                WhetherJoin(id,title);
            }
        });
    }

    /*判断是否加入*/
    private void WhetherJoin(final String id,final String title) {
        String token = AbSharedUtil.getString(SearchResultActivity.this, SharedConstants.USER_TOKEN);
        JudgeWhetherJoin judgeWhetherJoin = ApiWrapper.getInstance().create(JudgeWhetherJoin.class);
        Call<JudgeWhetherJoinBean> join = judgeWhetherJoin.getJoin(token, id);
        join.enqueue(new Callback<JudgeWhetherJoinBean>() {
            @Override
            public void onResponse(Call<JudgeWhetherJoinBean> call, Response<JudgeWhetherJoinBean> response) {
                JudgeWhetherJoinBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        /*说明用户已经加入圈子*/
                        intent.setClass(activity, Help_FeedBack_Activity.class);
                        intent.putExtra("circleId",id);
                        intent.putExtra("circleName",title);
                        intent.putExtra("login_find_uid",user_id);
                        startActivity(intent);
                    } else if (code == 1601) {
                            /*用户并没有加入该圈子*/
                        intent.setClass(activity, CircleFindDetailActivity.class);
                        intent.putExtra("circle_find_id", id);
                        startActivity(intent);
                    }
                } else {
                    MyToast.showToast(SearchResultActivity.this, "网络异常", Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onFailure(Call<JudgeWhetherJoinBean> call, Throwable t) {
                MyToast.showToast(SearchResultActivity.this, "网络异常", Toast.LENGTH_SHORT);
            }
        });
    }

    /*初始化RecyclerView*/
    private void initRecyclerView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        searchRecycler.setLayoutManager(linearLayoutManager);
    }

    /*初始化布局*/
    private void initView() {
        intents = new Intent();
        intent = getIntent();
        /*搜索的关键字*/
        searchkey = intent.getStringExtra("searchkey");
        circleEtSousuo.setText(searchkey);
        circleEtSousuo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager) SearchResultActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(
                                    SearchResultActivity.this
                                            .getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                    searchkey = circleEtSousuo.getText().toString().trim();
                    requestData();
                    return true;

                }
                return false;
            }
        });

        searchQuit.setOnClickListener(this);
    }

    /*填充数据*/
    private void fillData() {
        if (user.size() == 0 && circle.size() == 0) {
            MyToast.showToast(activity, "暂无搜索结果", Toast.LENGTH_SHORT);
            searchTvUser.setVisibility(View.INVISIBLE);
            searchRecycler.setVisibility(View.INVISIBLE);
            searchTvCircleName.setVisibility(View.INVISIBLE);
            searchLv.setVisibility(View.INVISIBLE);
            yonghuCirclr.setVisibility(View.INVISIBLE);
        } else if (user.size() == 0 && circle.size() != 0) {
            searchTvUser.setVisibility(View.GONE);
            searchRecycler.setVisibility(View.GONE);
            searchTvCircleName.setVisibility(View.VISIBLE);
            searchLv.setVisibility(View.VISIBLE);
            circleAdapter.addAll(circle);
        } else if (user.size() != 0 && circle.size() == 0) {
            searchTvUser.setVisibility(View.VISIBLE);
            searchRecycler.setVisibility(View.VISIBLE);
            userAdapter.addAll(user);
            searchTvCircleName.setVisibility(View.GONE);
            searchLv.setVisibility(View.GONE);
        } else if (user.size() != 0 && circle.size() != 0) {
            searchTvCircleName.setVisibility(View.VISIBLE);
            searchLv.setVisibility(View.VISIBLE);
            searchTvUser.setVisibility(View.VISIBLE);
            searchRecycler.setVisibility(View.VISIBLE);
            userAdapter.addAll(user);
            circleAdapter.addAll(circle);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            /*取消*/
            case R.id.search_quit:
                finish();
                break;
            case value:

                break;
        }
    }
}
